package q0024;
/*
 * @lc app=leetcode.cn id=24 lang=java
 *
 * [24] 两两交换链表中的节点
 *
 * https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
 *
 * algorithms
 * Medium (61.67%)
 * Likes:    268
 * Dislikes: 0
 * Total Accepted:    36.4K
 * Total Submissions: 58.8K
 * Testcase Example:  '[1,2,3,4]'
 *
 * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
 *
 * 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
 *
 *
 *
 * 示例:
 *
 * 给定 1->2->3->4, 你应该返回 2->1->4->3.
 *
 *
 */

class Solution {
    public ListNode swapPairs(ListNode head) {

        ListNode newHead = head;
        ListNode pre = null;
        while (null != head && null != head.next) {
            ListNode n2 = head.next;
            head.next = head.next.next;

            if (null == pre) {
                newHead = n2;
            } else {
                pre.next = n2;
            }

            n2.next = head;
            pre = head;
            head = head.next;
        }

        return newHead;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;

        ListNode listNode = new Solution().swapPairs(n1);

        while (null != listNode) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }

}

